package niu.fencer.tool.qrcode.util;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Encoder {

	public int total=2;
	public byte[][] encode(byte[] data, int splitSize,String fileName) {
		int len=data.length;
		fileName="gz1"+fileName;
		data=GZipUtil.compress(data);

		int numChunks =data.length/splitSize;
		int n=numChunks;
		if (data.length % splitSize > 0) {
			n++;
		}
		LogUtil.i("numChunks:"+n+",data.length:"+data.length+",len="+len);

		byte[][] rangeArray = new byte[n+1][]; //+1  save fileName
//		List<byte[]> list=new ArrayList<byte[]>();
		rangeArray[0] =concat2(n+1,0,fileName.getBytes());

		for (int i = 0; i < numChunks; i++) {
			int from = i * splitSize;
			rangeArray[i+1] =concat2(n+1,i+1, Arrays.copyOfRange(data, from, from + splitSize));
		}
		if(n>numChunks) {
			rangeArray[n] = concat2(n+1, n, Arrays.copyOfRange(data, numChunks * splitSize, data.length));
		}
		total=rangeArray.length;
		return rangeArray;
	}

	private byte[] concat2(int total,int index,byte[] splitedArray) {
		
		ByteBuffer dbuf = ByteBuffer.allocate(8+splitedArray.length);
		dbuf.putInt(total);
		dbuf.putInt(index);
		dbuf.put(splitedArray);
		return dbuf.array();
	}


	private int numberOfChunks(int length, int chunkLen) {
		int n = length / chunkLen;
		if (length % chunkLen > 0) {
			n++;
		}
		return n;
	}

	public static void main(String[] args) throws Throwable {


	}

}
